<template>
  <section>
    <!-- 面包屑 -->
     <breadcrumbs></breadcrumbs>
    <!-- 查询条件 -->
    <el-form ref="searchForm" :model="searchForm" label-width="100px" inline class="demo-form-inline" size="small" style="border-bottom: 1px solid #f6f6f6">
      <el-form-item label="活动时间" prop="date">
        <el-date-picker v-model="searchForm.date" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="searchForm.keyword" placeholder="标题/名师昵称"></el-input>
      </el-form-item>
      <el-form-item label="报名时间" prop="signDate">
        <el-date-picker v-model="searchForm.signDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="searchForm.state" placeholder="请选择状态">
          <el-option label="有效" value="1"></el-option>
          <el-option label="无效" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="课程类型" prop="type">
        <el-select v-model="searchForm.type" placeholder="请选择课程类型">
          <el-option label="培训" value="1"></el-option>
          <el-option label="研修" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="
            searchForm.current = 1;
            search();
          ">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <btns @exec="exec"></btns>
    <div class="data-container scroll-table">
      <div>
        <div class="ind-title lh50 f16">列表</div>
      </div>
      <el-table :data="tableData" ref="multipleTable" style="width: 100%" @selection-change="tableSelectionChange" row-key="ifId" border lazy
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column type="selection" width="80"> </el-table-column>
        <el-table-column prop="headImg" label="封面图">
          <template slot-scope="scope">
            <el-image style="width: 60px; height: 60px" :src="scope.row.headImg" fit="cover"></el-image>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="trainId" label="培训研修id" width="160"> </el-table-column> -->
        <el-table-column prop="teachId" label="名师id"> </el-table-column>
        <el-table-column prop="school" label="举办地址" width="100"> </el-table-column>
        <el-table-column prop="address" label="机构" width="150"> </el-table-column>
        <el-table-column prop="type" label="类型">
          <template slot-scope="scope">
            <span v-if="scope.row.type == 1">培训</span>
            <span v-if="scope.row.type == 2">研修</span>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="属性">
          <template slot-scope="scope">
            <span v-if="scope.row.category == 1">线上直播</span>
            <span v-if="scope.row.category == 2">线下活动</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题"> </el-table-column>
        <el-table-column prop="labels" label="标签">
          <template slot-scope="scope">
            <el-tag type="success" v-if="tag!=''" :key="index" v-for="(tag,index) in scope.row.labels.split(',')">{{tag}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="begintime" label="开始时间"> </el-table-column>
        <el-table-column prop="endtime" label="结束时间"> </el-table-column>
        <el-table-column prop="addtime" label="发起时间"> </el-table-column>
        <el-table-column prop="signBegintime" label="报名开始时间"> </el-table-column>
        <el-table-column prop="signEndtime" label="报名结束时间"> </el-table-column>
        <el-table-column prop="state" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.state == 1">启用</span>
            <span v-if="scope.row.state == 2">申请中</span>
            <span v-if="scope.row.state == 3">禁用</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <div>
              <el-button size="small" type="primary" @click="toDetail(scope.row)">详情</el-button>
              <el-button size="small" type="primary" @click="toTrainInfo(scope.row)">查看报名</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15, 20]"
                     :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!--新增修改界面-->
    <el-dialog :title="funTit == 'add' ? '新增' : '修改'" :visible.sync="addORUpdateVisible" width="700px" :close-on-click-modal="false" :before-close='clearAdd'>
      <el-form :model="trainForm" label-width="120px" :rules="trainFormRules" ref="trainForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="trainForm.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio v-model="trainForm.type" label="1">培训</el-radio>
          <el-radio v-model="trainForm.type" label="2">研修</el-radio>
        </el-form-item>
        <el-form-item label="封面" prop="headImg">
          <el-upload :action="uploadFile" list-type="picture-card" :on-remove="handleRemove" :on-success="handleAvatarSuccess" v-model="trainForm.headImg"
                     :limit="1" :file-list="filesEdit">
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">只能上传1图片</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="培训时间" prop="time">
          <el-date-picker v-model="trainForm.time" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['12:00:00']">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报名时间" prop="signTime">
          <el-date-picker v-model="trainForm.signTime" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['12:00:00']">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="举办地址" prop="address">
          <el-input v-model="trainForm.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="举办机" prop="school">
          <el-input v-model="trainForm.school" auto-complete="off"></el-input>
        </el-form-item>
        <!-- 添加老师 :loading="loading" :remote-method="remoteMethod" -->
        <el-form-item label="选择老师" :label-width="formLabelWidth" prop="teacherId">
          <el-select v-model="trainForm.teacherId" multiple filterable remote reserve-keyword placeholder="请输入关键词">
            <el-option v-for="item in options" :key="item.wxUserId" :label="item.nickname" :value="item.wxUserId"></el-option>
          </el-select>
        </el-form-item>
        <!-- 添加标签 -->
        <!-- :prop="'domains.' + index + '.value'" -->
        <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :label="'标签' + (Number(index) + 1)" :key="domain.key" :rules="{
            required: true,
            message: '标签内容不能为空',
            trigger: 'blur',
          }">
          <el-row>
            <el-col :span="10">
              <el-input v-model="domain.value"></el-input>
            </el-col>
            <el-col :span="2" :offset="1">
              <el-button type="danger" v-if="funTit!='detail'" @click.prevent="removeDomain(domain)">删除</el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <Editor ref="child" v-model="trainForm.content"></Editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="funTit!='detail'" @click="addDomain">新增标签</el-button>
        <el-button @click.native="clearAdd()">取消</el-button>
        <el-button type="primary" v-if="funTit!='detail'" @click.native="submit('trainForm')">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<style>
</style>
<script>
import mixins from "@/utils/mixins";
import btns from "@/components/btns.vue";
import breadcrumbs from "@/components/breadcrumbs.vue";
import Editor from '../../components/edit.vue'
export default {
  mixins: [mixins],
  components: {
    btns,
    Editor,
    breadcrumbs,
  },
  data() {
    return {
      loading: true,
      searchForm: {
        date: [],
        signDate: [],
        endTime: "",
        beginTime: "",
        signBeginTime: '',
        signEndTime: '',
        current: 1,
        size: 10,
        totalCount: "",
        keyword: "",
        state: "",
        type: '',
      },
      trainForm: {

      },
      trainFormRules: {
        title: [
          { required: true, message: "请输入标题", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择类型", trigger: "blur" },
        ],
        time: [
          { required: true, message: "请选择培训时间", trigger: "blur" },
        ],
        signTime: [
          { required: true, message: "请选择报名时间", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请填写举办地址", trigger: "blur" },
        ],
        school: [
          { required: true, message: "请填写举办机", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请填写内容", trigger: "blur" },
        ],
        headImg: [
          {
            required: true, message: '请上传头像', trigger: 'change'
          }
        ],
      },
      dynamicValidateForm: {
        domains: [],
      },
      options: [],
      filesEdit: [],

      userForm: {},
      funTit: 'add',
      uploadFile: this.GLOBAL.imgBaseUrl,
      changeHeadImgform: {},
      addORUpdateVisible: false,
      setFerrerDialog: false,
      addForm: {},
      addForRules: {
        "isReferrer": [{
          required: true,
          message: '请输入推荐值',
          trigger: 'blur'
        }],
      },
      formLabelWidth: '120px',
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
    };
  },
  created() {
    this.orderList(this.currentPage, this.pageSize);
    this.remoteMethod();
  },
  methods: {
    formatTime(date) {
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()
      return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':')
    },
    formatNumber(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    },
    remoteMethod() {
      // if (query !== '') {
      this.loading = true;
      this.$api.teacher
        .getTeacherList({
          beginTime: '',
          endTime: '',
          keyword: "",
        })
        .then((d) => {
          this.loading = false;
          this.options = d.data;
        })
        .catch((e) => {
          console.log(e);
        });
      // } else {
      //   this.options = [];
      // }
    },
    clearAdd() {
      if (this.$refs.hasOwnProperty("trainForm")) {
        this.$refs['trainForm'].resetFields();
      }
      this.trainForm = {}
      this.addORUpdateVisible = false;
      this.filesEdit = [];
      this.dynamicValidateForm.domains = [];
      // this.$refs.child.clearText();
      this.tableSelection = [];
      this.$refs.multipleTable.clearSelection();
    },
    add() {
      this.addORUpdateVisible = true;
      this.funTit = 'add'
    },
    toDetail(row) {
      this.tableSelection = [row]
      this.update()
      this.funTit = 'detail'
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let label = this.dynamicValidateForm.domains.map(e => {
            return e.value
          }) || ''
          let params = {
            address: this.trainForm.address,
            endTime: this.formatTime(this.trainForm.time[1]),
            beginTime: this.formatTime(this.trainForm.time[0]),
            content: this.trainForm.content,
            headImg: this.trainForm.headImg,
            school: this.trainForm.school,
            signBeginTime: this.formatTime(this.trainForm.signTime[0]),
            signEndTime: this.formatTime(this.trainForm.signTime[1]),
            title: this.trainForm.title,
            type: this.trainForm.type,
            labels: label.join(',') || '',
            teacherId: this.trainForm.teacherId,
          }
          // console.log('----------------', params);
          if (this.funTit == 'add') {
            this.$api.train
              .addTrain(params)
              .then((d) => {
                if (d.code == 200) {
                  this.clearAdd();
                  this.search();
                  this.$message.success('操作成功！');
                } else {
                  this.$message.error(d.msg);
                }
              })
              .catch((e) => {
                console.log(e);
              });
          } else {
            this.$api.train
              .editTrain(params)
              .then((d) => {
                if (d.code == 200) {
                  this.clearAdd();
                  this.$message.success('操作成功！');
                } else {
                  this.$message.error(d.msg);
                }
              })
              .catch((e) => {
                console.log(e);
              });
          }
        }
      })
    },
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
      }
    },
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: '',
        key: Date.now()
      });
    },
    handleRemove(file, fileList) {
      this.trainForm.headImg = '';
    },
    handleAvatarSuccess(res, file) {
      this.trainForm.headImg = res.replace(this.previewPicture, '');
    },
    tableSelectionChange(val) {
      this.tableSelection = val;
    },
    exec(fun) {
      if (this[fun]) {
        this.funTit = fun;
        this[fun]();
      } else {
        this.$message.error("方法未定义");
      }
    },
    toTrainInfo(row) {
      this.$router.push({
        path: `/train/trainSignList`,
        query: { id: row.trainId },
      });
    },
    search() {
      this.orderList(this.currentPage, this.pageSize);
    },
    orderList(cur, ss) {
      if (this.searchForm.date && this.searchForm.date.length == 2) {
        this.searchForm.beginTime = this.format(this.searchForm.date[0]);
        this.searchForm.endTime = this.format(this.searchForm.date[1]);
      }
      if (this.searchForm.signDate && this.searchForm.signDate.length == 2) {
        this.searchForm.signBeginTime = this.format(this.searchForm.signDate[0]);
        this.searchForm.signEndTime = this.format(this.searchForm.signDate[1]);
      }

      this.$api.train
        .getTrainList({
          current: cur,
          size: ss,
          beginTime: this.searchForm.beginTime,
          endTime: this.searchForm.endTime,
          signBeginTime: this.searchForm.signBeginTime,
          signEndTime: this.searchForm.signEndTime,
          keyword: this.searchForm.keyword,
          state: this.searchForm.state,
          type: this.searchForm.type,
        })
        .then((d) => {
          this.tableData = d.data;
          this.total = d.totalCount;
        })
        .catch((e) => {
          console.log(e);
        });
    },
    update() {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }
      this.trainForm.type = this.tableSelection[0].type + '';
      this.trainForm.address = this.tableSelection[0].address;
      this.trainForm.content = this.tableSelection[0].content;
      this.trainForm.school = this.tableSelection[0].school;
      this.trainForm.title = this.tableSelection[0].title;
      this.trainForm.teacherId = [this.tableSelection[0].teachId]
      // this.tableSelection[0].teachId + ''.split(",").forEach(e => {
      //   if (e != "") {
      //     console.log('========', e)
      //     this.trainForm.teacherId.push(e)
      //   }
      // })
      console.log(this.tableSelection[0].begintime, [new Date(this.tableSelection[0].begintime), new Date(this.tableSelection[0].endtime)]);
      this.trainForm.time = [new Date(this.tableSelection[0].begintime), new Date(this.tableSelection[0].endtime)]
      this.trainForm.signTime = [new Date(this.tableSelection[0].signBegintime), new Date(this.tableSelection[0].signEndtime)]
      this.tableSelection[0].labels.split(',').forEach(e => {
        if (e != "")
          this.dynamicValidateForm.domains.push({
            value: e,
            key: Date.now()
          })
      })
      let file = this.tableSelection[0].headImg.split(",");
      file.forEach((item, index) => {
        if (item != "") {
          this.filesEdit.push({
            url: item,
            index: index
          })
        }
      });
      this.addORUpdateVisible = true;
      this.funTit = 'update'
    },
    //启用
    enable() {
      if (this.tableSelection.length < 1) {
        this.$message.error("请选择要操作的数据！");
        return;
      }
      let ids = this.tableSelection.map((e) => {
        return e.state;
      });
      let trainId = this.tableSelection.map((e) => {
        return e.trainId;
      });
      let s = new Set(ids);
      if ([...s].length != 1) {
        return this.$message.error("请选择状态一致的数据！");
      }
      if ([...s][0] != 3) {
        return this.$message.error("请选择状态为禁用数据！");
      }
      this.$confirm("确认要启用这个培训, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.train
            .enableTrain({
              trainIds: trainId.join(","),
              state: 1, //状态 2禁用 1启用
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "启用成功",
                });
                this.orderList(this.currentPage, this.pageSize);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消启用");
        });
    },
    //禁用
    disable() {
      if (this.tableSelection.length < 1) {
        this.$message.error("请选择要操作的数据！");
        return;
      }
      let ids = this.tableSelection.map((e) => {
        return e.state;
      });
      let trainId = this.tableSelection.map((e) => {
        return e.trainId;
      });
      let s = new Set(ids);
      if ([...s].length != 1) {
        return this.$message.error("请选择状态一致的数据！");
      }
      if ([...s][0] != 1) {
        return this.$message.error("请选择状态为启用数据！");
      }
      this.$confirm("确认要禁用这个培训, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.train
            .enableTrain({
              trainIds: trainId.join(","),
              state: 3, //状态 2禁用 1启用
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "禁用成功",
                });
                this.orderList(this.currentPage, this.pageSize);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消禁用");
        });
    },
    handleReset() {
      this.searchForm = {
        keyword: "",
        state: '',
        type: '',
      };
      (this.endTimee = ""), (this.beginTimee = ""), this.search();
    },
    handleSizeChange(v) {
      console.log(v)
      this.searchForm.size = v;
      this.orderList(this.searchForm.current, v);
    },
    handleCurrentChange(v) {
      this.searchForm.current = v;
      this.orderList(v, this.searchForm.size, v);
    },
  },
};
</script>
<style scoped>
.dialog-footer {
  margin-top: 50px;
}
.top-box {
  width: 100%;

  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 80px;
}

.top-item {
  border: 1px rgb(189, 185, 185) solid;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50%;
  margin-right: 100px;
}
.top-icon {
  width: 30%;
  height: 30%;
  margin-right: 30px;
  margin-left: 30px;
}
.fontText {
  font-size: 20px;
}

.fontTop {
  font-size: 40px;
}
.f18 {
  font-size: 25px;
  font-weight: 700;
}
.mgb-20 {
  font-size: 16px;
}
</style>
